<template>
    <div class="page_header">
        <transition name="fade">
            <div v-show="visible" class="header_warp">
                <div class="container">
                    <div class="row">
                        <div class="col-12">
                            <div class="my_header">
                                <router-link to="/">
                                    <div class="logo">{{ t('systemName') }}</div>
                                </router-link>
                                <div ref="nav_target" class="nav_list">
                                    <ul>
                                        <li>
                                            <router-link to="/">
                                                {{ t('home') }}
                                            </router-link>
                                        </li>
                                        <li v-if="meetingInfoNav">
                                            <router-link :to="meetingInfoNav.path">
                                                {{ getNavTitle(meetingInfoNav) }}
                                            </router-link>
                                        </li>
                                        <li>
                                          <router-link to="/article/list">
                                            {{ t('articleList') }}
                                          </router-link>
                                        </li>
                                        <li>
                                            <router-link to="/notice/list">
                                                {{ t('announcements') }}
                                            </router-link>
                                        </li>
                                        <li v-if="adNav">
                                            <router-link :to="adNav.path">
                                                {{ getNavTitle(adNav) }}
                                            </router-link>
                                        </li>
                                        <li>
                                            <router-link to="/contact">
                                                {{ t('contactUs') }}
                                            </router-link>
                                        </li>
                                        <li v-if="nav_top.length > top_max">
                                            <div ref="more" class="more" @click="change()">
                                                <span class="more_text">{{ t('more') }}</span>
                                                <span class="caret" v-bind:style="
												{transform: 'rotate('+ angle1 +'deg)'}" />
                                            </div>
                                            <div v-show="show" class="dropdown">
                                                <div v-if="i >= top_max" class="item" v-for="(o,i) in nav_top">
                                                    <router-link :to="o.path">
                                                        {{ getNavTitle(o) }}
                                                    </router-link>
                                                </div>
                                            </div>
                                        </li>
                                    </ul>
                                </div>
                                <div class="user" v-if="!user.user_id">
                                    <router-link class="ml" to="/account/login">
                                        {{ t('login') }}
                                    </router-link>
                                    <router-link class="ml" to="/account/register">
                                        {{ t('register') }}
                                    </router-link>
                                </div>
                                <div ref="my" v-else class="user">
                                    <div ref="own" class="own" @click="my()">
                                        <span class="own_text">{{ t('myAccount') }}</span>
                                        <span class="caret" v-bind:style="
												{transform: 'rotate('+ angle2 +'deg)'}"/>
                                    </div>
                                    <div v-show="my_show" class="dropdown">
                                        <div class="my_item" v-for="(o,i) in my_nav" :key="i">
                                            <router-link :to="o.url">
                                                {{ t(o.nameKey) }}
                                                <span v-if="o.url === '/user/messages' && unreadMessageCount > 0" class="message_badge">{{ unreadMessageCount }}</span>
                                            </router-link>
                                        </div>
                                        <div class="my_item">
                                            <div @click="to_admin()">
                                                {{ t('personalCenter') }}
                                            </div>
                                        </div>
                                        <div class="my_item" @click="sign_out()">
                                            <router-link to="/">
                                                {{ t('logout') }}
                                            </router-link>
                                        </div>
                                    </div>
                                </div>
                                <div ref="mini" class="mini_nav" @click="open_mini()">
                                    <div ref="mini" class="mini">
                                        <span class="mini_text">{{ t('menu') }}</span>
                                        <span class="caret" v-bind:style="
												{transform: 'rotate('+ angle3 +'deg)'}"/>
                                    </div>
                                </div>
                                <!-- 语言切换按钮 -->
                                <div class="language-switch" @click="toggleLanguage">
                                    <span class="lang-text">{{ currentLanguage === 'zh' ? '中文' : 'English' }}</span>
                                    <span class="lang-icon">🌐</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </transition>
    </div>

</template>

<script>

    import mixin from "@/mixins/component.js";
    import mixinI18n from "@/mixins/i18n.js";

    const OFFSET_HEIGHT = 60;
    export default {

        mixins: [mixin, mixinI18n],

        data() {
            return {
                top_max: 15,
                angle1: 0,
                angle2: 0,
                angle3: 0,
                visible: true,
                show: false,
                my_show: false,
                nav_top: [
                ],
                meetingInfoNav: null,
                adNav: null,
                my_nav: [
                    {
                        nameKey: "myAccount",
                        url: "/user/index",
                    },
                    {
                        nameKey: "myMessages",
                        url: "/user/messages",
                        badge: 0, // 未读消息数
                    },
                    {
                        nameKey: "myFavorites",
                        url: "/user/collect",
                    },
                ],
                unreadMessageCount: 0,
                not_login_dropdown: [],
                showInput: false,
                logo:""
            };
        },

        methods: {
            // 切换语言（使用全局混入的 t() 函数）
            toggleLanguage() {
                const newLang = this.currentLanguage === 'zh' ? 'en' : 'zh';
                this.$store.commit('set_language', newLang);
                // 触发页面更新
                this.$forceUpdate();
                // 更新页面标题
                this.updatePageTitle();
            },
            // 获取导航标题（支持双语和路径映射）
            getNavTitle(navItem) {
                if (!navItem) return '';
                
                // 先尝试解析双语JSON
                let title = navItem.page_title || navItem.mod_name || '';
                if (title) {
                    const parsed = this.$getBilingualText(title);
                    if (parsed && parsed !== title) {
                        return parsed;
                    }
                }
                
                // 如果解析失败或不是JSON，尝试路径映射
                const pathMap = {
                    '/meeting_information/list': this.t('meetingList'),
                    '/ad/list': this.t('advertisementList'),
                    '/article/list': this.t('articleList'),
                    '/notice/list': this.t('noticeList')
                };
                
                if (navItem.path && pathMap[navItem.path]) {
                    return pathMap[navItem.path];
                }
                
                // 如果路径映射也没有，尝试标题映射
                const titleMap = {
                    '会议信息列表': this.t('meetingList'),
                    '广告列表': this.t('advertisementList'),
                    '文章列表': this.t('articleList'),
                    '公告列表': this.t('noticeList')
                };
                
                if (title && titleMap[title]) {
                    return titleMap[title];
                }
                
                // 最后返回原标题
                return title || '';
            },

            to_admin(){
                let token = $.db.get("token");
                if (token){
                    location.href = "http://localhost:8080/?token="+token;
                }
            },

            // 获取导航栏
            async get_nav_top() {
                var auth = this.$store.state.web.auth;

            	if(auth.length > 0){
					var arr = [];
            		for(var i=0;i<auth.length;i++){
            			var o = auth[i];
            			if(o["position"] == "top"){
            				arr.push(o);
            			}
            		}
	            	// 导航栏不显示会议详情（但不影响通过列表卡片跳转）
	            	var filtered = arr.filter(function(o){ return o.path !== '/meeting_information/details'; });
	            	// 提取会议信息列表和广告列表
	            	this.meetingInfoNav = filtered.find(function(o) { return o.path === '/meeting_information/list'; }) || null;
	            	this.adNav = filtered.find(function(o) { return o.path === '/ad/list'; }) || null;
	            	// 保存其他菜单项到 nav_top（用于下拉菜单）
	            	this.nav_top = filtered.filter(function(o) { 
	            		return o.path !== '/meeting_information/list' && o.path !== '/ad/list'; 
	            	});
            	}else{
            		var user_group = this.$store.state.user.user_group || $.db.get("user_group") || "游客";
					var res = await this.$get("~/api/auth/get_list", {
            		    user_group,
						"get": 1,
            		    "position": "top",
						"page": ""
            		});
					if(res.result && res.result.list){
	            		var list = res.result.list;
	            		// 导航栏不显示会议详情（但不影响通过列表卡片跳转）
	            		var filtered = list.filter(function(o){ return o.path !== '/meeting_information/details'; });
	            		// 提取会议信息列表和广告列表
	            		this.meetingInfoNav = filtered.find(function(o) { return o.path === '/meeting_information/list'; }) || null;
	            		this.adNav = filtered.find(function(o) { return o.path === '/ad/list'; }) || null;
	            		// 保存其他菜单项到 nav_top（用于下拉菜单）
	            		this.nav_top = filtered.filter(function(o) { 
	            			return o.path !== '/meeting_information/list' && o.path !== '/ad/list'; 
	            		});
	            	}
            	}
            },

            sign_out() {
                this.$store.commit("sign_out");
				this.$get("~/api/user/quit?",{},(res)=>{
					console.log(res);
				})
                location.reload();
                // location.href = location.href
            },


            change() {
                var _this = this;

                _this.show = !_this.show;
                var angle = _this.angle1;
                angle = angle + 180;
                if (angle === 360) {
                    _this.angle1 = 0;
                } else {
                    _this.angle1 = angle;
                }
            },

            my() {
                var _this = this;
                if (_this.angle3 === 180) {
                    _this.$refs.nav_target.style.display = 'none';
                    _this.angle3 = 0;
                }
                _this.my_show = !_this.my_show;
                var angle = _this.angle2;
                angle = angle + 180;
                if (angle === 360) {
                    _this.angle2 = 0
                } else {
                    _this.angle2 = angle;
                }
            },

            open_mini() {
                var _this = this;
                if (_this.my_show) {
                    _this.my_show = false;
                }
                var angle = _this.angle3;
                angle = angle + 180;
                if (angle === 360) {
                    _this.$refs.nav_target.style.display = 'none';
                    _this.angle3 = 0;
                } else {
                    _this.$refs.nav_target.style.display = 'block';
                    _this.angle3 = angle;
                }
            },

            // 滚动隐藏
            handleScroll() {
                const offsetTop = window.pageYOffset || document.documentElement.scrollTop;
                this.visible = offsetTop < OFFSET_HEIGHT;
            },

            keep(width) {
                var _this = this;
                var display = _this.$refs.nav_target.style.display;
                if (width >= 960 && display === 'none') {
                    _this.$refs.nav_target.style.display = 'block';
                }
            },
            // 加载未读消息数量
            async loadUnreadCount() {
                const userId = this.$store.state.user?.user_id;
                if (!userId || userId === 0) {
                    return;
                }
                
                try {
                    const json = await this.$get(`~/api/user_message/get_unread_count?user_id=${userId}`);
                    if (json.result !== undefined) {
                        this.unreadMessageCount = Number(json.result) || 0;
                        // 更新菜单中的badge
                        const messageNav = this.my_nav.find(n => n.url === '/user/messages');
                        if (messageNav) {
                            messageNav.badge = this.unreadMessageCount;
                        }
                    }
                } catch (error) {
                    console.error('获取未读消息数量失败:', error);
                }
            }

        },

        created() {
            this.get_nav_top();
            this.logo = document.logo;
            this.loadUnreadCount();
        },

        mounted() {

            window.onresize = () => {
                return (() => {
                    this.keep(document.body.clientWidth);
                })();
            };
            window.addEventListener('scroll', this.handleScroll);
            document.addEventListener('mouseup', (e) => {
                const _this = this;
                let tree = _this.$refs.more;
                let my = _this.$refs.my;
                if (tree) {
                    if (!tree.contains(e.target)) {
                        _this.show = false;
                        _this.angle1 = 0;
                    }
                }
                if (my) {
                    if (!my.contains(e.target)) {
                        _this.my_show = false;
                        _this.angle2 = 0;
                    }
                }
            });
            
            // 定期刷新未读消息数量
            this.messageRefreshInterval = setInterval(() => {
                this.loadUnreadCount();
            }, 30000); // 每30秒刷新一次
        },

        destroyed() {
            window.removeEventListener('scroll', this.handleScroll);
            if (this.messageRefreshInterval) {
                clearInterval(this.messageRefreshInterval);
            }
        },

    };

</script>

<style scoped="scoped">

    .header_warp {
        background-color: var(--color_primary);
        height: 4rem;
        color: white;
        font-weight: 600;
        box-shadow: 0 0.1rem 0.3rem rgba(0, 0, 0, 0.15);
    }

    .my_header {
        display: block;
        height: 4rem;
    }

    .logo {
        font-size: 1.3rem;
        float: left;
        height: 4rem;
        width: 8rem;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .nav_list {
        float: left;
    }

    .caret {
        margin-left: 0.875rem;
        display: inline-block;
        width: 0;
        height: 0;
        vertical-align: middle;
        border-top: 4px dashed;
        border-right: 4px solid transparent;
        border-left: 4px solid transparent;
        transition: transform 0.2s;
    }

    .fade-enter-active,
    .fade-leave-active {
        transition: all 0.5s;
    }

    .fade-enter,
    .fade-leave-to {
        transform: translateY(-60px);
    }

    ul {
        margin: 0;
        padding: 0;
    }

    li {
        float: left;
        list-style: none;
    }

    li a {
        color: #ddd;
        height: 4rem;
        width: 5rem;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .more {
        height: 4rem;
        width: 4rem;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .caret:hover,
    .more:hover {
        cursor: pointer;
        color: #909399;
    }

    .dropdown {
        position: absolute;
        top: 5rem;
        left: -1.5rem;
        height: auto;
        background-color: white;
        width: 8rem;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
        display: flex;
        border-radius: 0.3rem;
        flex-direction: column;
        font-size: 0.8rem;
    }

    .dropdown .my_item a {
        color: #000 !important;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 3rem;
        position: relative;
    }
    
    .message_badge {
        position: absolute;
        top: 0.5rem;
        right: 1rem;
        background: #f56c6c;
        color: #fff;
        font-size: 0.7rem;
        padding: 0.1rem 0.4rem;
        border-radius: 10px;
        min-width: 1.2rem;
        text-align: center;
        line-height: 1.4;
    }

    .dropdown .my_item a:hover {
        border-radius: 0.3rem;
        color: #fff !important;
    }

    .dropdown .my_item div {
        color: #000 !important;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 3rem;
        cursor: pointer;
    }

    .dropdown .my_item div:hover {
        border-radius: 0.3rem;
        color: #fff !important;
    }

    .dropdown .my_item:hover {
        background-color: #909399;
    }

    .dropdown .item a {
        color: #000 !important;
        margin: auto;
        height: 3rem;
        width: 100%;
    }

    .dropdown .item a:hover {
        border-radius: 0.3rem;
        color: #fff !important;
        background-color: #909399;
    }

    .user {
        position: relative;
        margin-left: 2rem;
        height: 4rem;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        float: right;
        width: 6rem;
        margin-right: 1rem;
    }

    .own:hover {
        color: #909399;
        cursor: pointer;
    }


    /* 语言切换按钮样式 */
    .language-switch {
        float: right;
        margin-right: 1rem;
        height: 4rem;
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 0 0.75rem;
        border-radius: 4px;
        transition: background-color 0.3s;
    }

    .language-switch:hover {
        background-color: rgba(255, 255, 255, 0.1);
    }

    .lang-text {
        color: white;
        font-size: 0.9rem;
        margin-right: 0.5rem;
        font-weight: 500;
    }

    .lang-icon {
        font-size: 1.2rem;
        line-height: 1;
    }

    .mini_nav {
        display: none;
    }

    @media (max-width: 1200px) {
        .user {
            margin-left: 0;
        }
    }

    @media (max-width: 960px) {

        .nav_list {
            color: var(--color_primary);
            padding-top: 3.5rem;
            background-color: white;
            display: none;
            position: absolute;
            top: 5rem;
            right: 6rem;
            width: 12rem;
            /*height: 20rem;*/
            border-radius: 0.5rem;
            box-shadow: 0 0.1rem 0.3rem rgba(0, 0, 0, 0.15);
        }

        .nav_list ul {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .dropdown {
            left: -2rem;
        }

        .mini_nav {
            float: right;
            width: 4rem;
            height: 4rem;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .dropdown {
            left: -4rem;
            width: 12rem;
        }

        .user .dropdown {
            left: -3rem;
            width: 8rem;
        }

    }

</style>
